/*
 * @Date: 2023-03-27 16:35:00
 * @LastEditTime: 2023-06-22 12:23:02
 * 介绍:系统钩子
 */
import { Locale } from "vant";
import enUS from "vant/es/locale/lang/en-US";
import zhCN from "vant/es/locale/lang/zh-CN";
import zhTW from "vant/es/locale/lang/zh-TW";
import useSysStore from "@@/store/useSysStore";
import useUserinfoStore from "@@/store/useUserinfoStore";
import { toast } from "@@/hooks/vantHooks";
import { i18n } from "@@/language";
import PubSub from "pubsub-js";
import type { StoreDefinition } from "pinia";
import useBalanceStore from "@@/store/useBalanceStore";
import { close } from "@@globalView/invite";
import { sys } from "@@/enum/pubsub";
//@ts-ignore
const { t } = i18n.global;

/**登录完成 */
export async function logined() {
  window.isLogined = true;
  const balanceStore = useBalanceStore();
  const userinfoStore = useUserinfoStore();
  await Promise.all([userinfoStore.getUserinfo(), balanceStore.getCoinEnum()]);
  toast.close();
  close();
  // setTimeout(() => {
  //   toast.success(t("lian-jie-cheng-gong"));
  // }, 1000);
  PubSub.publish(sys.logined);
  return true;
}

/**
 * * 重置所有本地仓库
 * @param 不包括的store $id数组
 * @argument 默认不包括用户设置
 */
export function resetStore(exclude?: string[], excludeDefault = ["SysStore"]) {
  const sotres = Object.values(
    import.meta.glob("@@/store/**.ts", { eager: true })
  );
  console.log("重置所有store");
  sotres.forEach((val: any) => {
    const useStore = val.default as StoreDefinition;
    if (
      exclude?.includes(useStore.$id) ||
      excludeDefault.includes(useStore.$id)
    )
      return;
    const store = useStore();
    store.$reset();
  });
}

/**
 * * 系统装载成功
 * @param callback 回调
 * @argument 登录成功后调用，包括重新登录后
 */
export function sysLoad(callback: (a: string, v: any) => any) {
  let mySub: string;
  onMounted(() => {
    if (window.isLogined) {
      callback(sys.logined, undefined);
    }
    mySub = PubSub.subscribe(sys.logined, callback);
  });
  onUnmounted(() => {
    PubSub.unsubscribe(mySub);
  });
}
/**切换语言 */
export function changeLang(langKey: string | undefined) {
  try {
    const _langKey = langKey as keyof typeof langEnum;
    const sysStore = useSysStore();
    langKey ??= import.meta.env.VITE_DEFAULT_LANG;
    console.log(`切换语言${langKey}`);
    const { locale } = i18n.global;
    locale.value = langKey;
    const langEnum = {
      "en-US": {
        key: "en-US",
        raw: enUS,
        apiLang: "en",
      },
      "zh-CN": {
        key: "zh-CN",
        raw: zhCN,
        apiLang: "zh-CN",
      },
      "zh-TW": {
        key: "zh-TW",
        raw: zhTW,
        apiLang: "zh-CN",
      },
    };
    Locale.use(langEnum[_langKey].key, langEnum[_langKey].raw);
    sysStore.setSetting({ language: langKey });
    sysStore.setReqHeader({ language: langEnum[_langKey].apiLang });
    PubSub.publish(sys.changeLang);
  } catch (error) {
    console.warn(`切换语言失败${langKey}`, error);
  }
}
